<template>
  <div class="media-input">
    <div class="tabs">
      <div
        class="tab"
        :class="{ active: type === tab.key }"
        v-for="tab in tabs"
        :key="tab.key"
        @click="type = tab.key"
      >
        {{ tab.label }}
      </div>
    </div>

    <template v-if="type === 'mp3'">
      <div class="flex">
        <div style="margin: 10px 13px; text-align: center">
          <!-- <el-upload
    class="avatar-uploader"
    action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload> -->
          <el-upload
            ref="upload"
            class="upload-demo"
            :action="''"
            :file-list="fileList"
            :on-change="handleChange"
            accept=".jpg,.jpeg,.png,.mp3,.mp4"
            :auto-upload="false"
            :show-file-list="false"
            :data="formData"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>

            <!-- <el-button v-if="fileList.length > 0" slot="append" @click="handleUpload" :disabled="uploading" :loading="uploading">上传到OSS</el-button> -->
          </el-upload>
          <div>上传文件</div>
        </div>
        <div
          v-for="item in listData"
          :key="item.id"
          style="width: 150px; text-align: center; margin: 10px 13px"
          class="image-container"
        >
          <div>
            <div @click="toselet(item)" v-if="item.fileSuffix === 'mp3'">
              <img
                src="../../../assets/musicd.png"
                alt=""
                style="width: 150px; height: 150px"
              />
              <div class="overlay">
                <div class="selector">
                  <!-- 选择框 -->
                  <el-checkbox-group
                    v-model="checked1"
                    :max="2"
                    @change="checkClick(item)"
                  >
                    <el-checkbox :label="item.id" />
                  </el-checkbox-group>
                </div>
                <div class="info">
                  <!-- 图片信息 -->
                  <span>大小:{{ item.fileSize }}M</span>
                  <span>上传用户:{{ item.createdAccount }}</span>
                </div>
              </div>
            </div>
            <div v-if="item.isFile === 0">
              <img
                src="../../../assets/upload-text.png"
                alt=""
                style="width: 150px; height: 150px"
                @click="openClick(item.id)"
              />
            </div>
            <div class="hiddn">
              {{ item.name }}
            </div>
          </div>
        </div>
      </div>
      <div></div>

      <!-- <Input v-model:value="videoSrc" placeholder="请输入视频地址，e.g. https://xxx.mp4"></Input> -->
      <div class="btns">
        <Button @click="emit('close')" style="margin-right: 10px">取消</Button>
        <Button type="primary" @click="insertAudio()">确认</Button>
      </div>
    </template>
  </div>
</template>
<script lang="ts" setup>
import { unref, onMounted, ref } from "vue";
import OSS from "ali-oss";
import { sourceMaterial, getCredit } from "@/api/facility/index";
import { Button, Input, message } from "ant-design-vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { sourceMaterialPage } from "@/api/facility";
import { decrypt } from "../../../utils/crypto.ts";

const imageUrl = ref("");
const checked1 = ref<any[]>([]);

const infoVisible = ref(false);
type TypeKey = "video" | "audio" | "image";

interface TabItem {
  key: TypeKey;
  label: string;
}
import type { UploadProps, UploadUserFile } from "element-plus";
const fileList = ref([]);
const uploadList = ref([]);
const formData = ref({});
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const hovered = ref(true); // 鼠标是否移入
const selectimg = ref("");
var types = ref<any>();
const srcList: any = [];
const checkClick = (item: any) => {
  types.value = item.fileSuffix;
  selectimg.value = item.fileUrl;
  videoSrc.value = item.fileUrl;
  fileSize.value = item.fileSize;
  name.value = item.name;
};

function toselet(item: any) {
  checked1.value = [item.id];
  checkClick(item);
}
const OSSKEY = ref<any>({});
const key = ref<any>("");
const iv = ref<any>("");
// 获取阿里云key
const getCredits = async () => {
  let res = await getCredit();
  OSSKEY.value = res.data.data;
  key.value = decrypt(res.data.data.accessKeyId);
  iv.value = decrypt(res.data.data.accessKeySecret);
};

const ossClient = (
  accessKeyId: string = unref(key),
  accessKeySecret: string = unref(iv)
) => {
  return new OSS({
    accessKeyId,
    accessKeySecret,
    bucket: "kpen",
    region: "oss-cn-shenzhen",
    secure: true,
  });
};
// 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
function handleChange(file: {
  raw: { type: string; name: any };
  size: number;
  name: any;
  status: string;
  percent: number;
  type: any;
}) {
  // 文件类型image/png"
  if (
    file.raw.type !== "image/png" &&
    file.raw.type !== "image/jpeg" &&
    file.raw.type !== "image/jpg" &&
    file.raw.type !== "video/mp4" &&
    file.raw.type !== "audio/mpeg" &&
    file.raw.type !== "application/pdf"
  ) {
    ElMessage.success("仅允许选择视频（mp4）、音频(mp3)、图片(jpg、jpeg、png)");
    return;
  }
  const uploadSizeLimit = file.raw.type === "image" ? 10 : 200; // 限制图片 20MB，视频音频 200MB
  const fileName = file.name;

  const fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
  if (file.size > uploadSizeLimit * 1024 * 1024) {
    ElMessage.success(`文件大小不能超过 ${uploadSizeLimit}MB`);
    return false;
  }
  if (file.status === "ready") {
    const currentDate = new Date();
    const year = currentDate.getFullYear(); // 获取当前年份
    const month = currentDate.getMonth() + 1; // 获取当前月份，需要注意月份从 0 开始计数
    const day = currentDate.getDate(); // 获取当前日
    const fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
    const storeAs = `${year}/${month}/${day}/${Date.now()}${"."}${fileExtension}`;
    const timestamp = Date.now();
    let startTime = Date.now(); // 发送上传请求之前的时间戳
    // 发送上传请求
    // ...
    // 请求完成并得到响应后
    let endTime = Date.now(); // 请求完成时间的时间戳
    let duration = Math.floor(Math.random() * 900) + 100; // 计算请求的总时间
    let fileSize = file.size; // 获取文件大小，单位是字节

    const upOptions = {
      secure: true,
      progress: (progressEvent: { loaded: number; total: number }) => {
        const percent = (progressEvent.loaded / progressEvent.total) * 100;
        file.percent = Math.floor(percent);
      },
      meta: {
        year: new Date().getFullYear(),
        month: new Date().getMonth() + 1,
        timestamp,
      },
    };
    const putOptions = {
      mime: file.type,
      contentDisposition: `inline; filename="${storeAs}"`,
      headers: {
        "Cache-Control": "max-age=31536000",
      },
    };
    ossClient()
      .multipartUpload(storeAs, file.raw, putOptions, upOptions, {})
      .then(async (result: { res: { requestUrls: any[]; status: number } }) => {
        formData.value.type = file.raw.type;
        formData.value.url = ossClient().signatureUrl(storeAs, {
          expires: 3600,
        });

        if (result.res.status == 200) {
          let url = result.res.requestUrls[0];
          var baseURL = url.split("?")[0]; //把?后面的截取掉
          url = baseURL;
          srcList.value = baseURL;
          let data = {
            directoryId: pidss.value, //目录id
            fileSource: 0, //文件来源
            fileUrl: baseURL, //文件路径
            name: file.raw.name,
            fileSuffix: fileExtension,
            isFile: 1,
          };
          let res = await sourceMaterial(data);
          ElMessage.success("上传成功");
          paging();
        }
      })
      .catch((error: { code: string }) => {
        if (error && error.code === "RequestAbortedError") {
          ElMessage.warning("取消上传");
        } else {
          ElMessage.error("上传失败，请稍后再试");
        }
        console.error(error);
      });
  }
}

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  _response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};
const showInfo = (_hide: any) => {
  infoVisible.value = _hide;
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (_rawFile) => {
  // if (rawFile.type !== 'image/jpeg') {
  //   ElMessage.error('Avatar picture must be JPG format!')
  //   return false
  // } else if (rawFile.size / 1024 / 1024 > 2) {
  //   ElMessage.error('Avatar picture size can not exceed 2MB!')
  //   return false
  // }
  // return true
};

const emit = defineEmits<{
  (
    event: "insertVideo",
    data: { src: string; fileSize: string; name: string }
  ): void;
  (event: "insertAudio", payload: string): void;
  (event: "close"): void;

  (event: "insertImage", payload: string): void;
  (event: "close"): void;
}>();
var pageSize4 = ref(10);
var currentPage4 = ref(1);
var pidss = ref(16);
var total = ref(16);
var listData = ref();
const openClick = (id: any) => {
  pidss.value = id;
  paging();
};
// 分页
const paging = async () => {
  const pageSize = pageSize4.value;
  const pageNum = currentPage4.value;
  let data = {
    directoryId: pidss.value,
    pageSize,
    pageNum,
    fileType: "",
    keyword: "",
  };
  let res = await sourceMaterialPage(data);
  if (res.data.code == 1) {
    total.value = res.data.data.totalElements;
    // listData.value = res.data.data.content.filter( (v:any) => v.fileSuffix !="mp4");
    listData.value = res.data.data.content.filter(
      (v: any) =>
        v.fileSuffix != "mp4" &&
        v.fileSuffix != "png" &&
        v.fileSuffix != "jpeg" &&
        v.fileSuffix != "jpg" &&
        v.fileSuffix != "pdf"
    );
  }
};
const type = ref<TypeKey>("mp3");

const videoSrc = ref();
const audioSrc = ref(
  "https://freesound.org/data/previews/614/614107_11861866-lq.mp3"
);
const name = ref("");
const fileSize = ref("");
const tabs: TabItem[] = [{ key: "audio", label: "音频" }];

const insertAudio = () => {
  if (types.value !== "mp3") return ElMessage.error("请选择音频文件");
  checked1.value = [];
  if (!selectimg.value) {
    ElMessage.error("插入音频失败");
    return;
  } else {
    ElMessage.success("插入音频成功");
  }
  emit("insertAudio", selectimg.value, fileSize.value, name.value);
  types.value = "";
  selectimg.value = "";
  videoSrc.value = "";
  fileSize.value = "";
  name.value = "";
};

onMounted(() => {
  paging();
  getCredits();
});
</script>

<style lang="scss" scoped>
.el-checkbox__input.is-bordered .el-checkbox__inner {
  border-color: #c0c4cc;
}

.el-checkbox__input.is-checked.is-bordered .el-checkbox__inner {
  background-color: #409eff;
  border-color: #409eff;
}

.el-icon-check {
  font-size: 12px;
  color: #fff;
}
::v-deep .el-checkbox.is-bordered {
  padding: 0 15px 0 9px;
  border: none;
  box-sizing: border-box;
}

::v-deep .el-checkbox__label {
  display: inline-block;
  padding-left: 8px;
  line-height: 1;
  font-size: var(--el-checkbox-font-size);
  display: none;
}

::v-deep .el-radio__inner {
  border-radius: 0;
}

::v-deep .el-radio__input.is-checked .el-radio__inner::after {
  content: "\00a0"; /* 添加一个空格 */
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #ffff; /* 勾选标识颜色 */
  border-radius: 50%;
  width: 10px;
  height: 10px;
}

.image-container {
  position: relative;
  width: 150px;
  height: 150px;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  background-color: rgba(0, 0, 0, 0.8);
  color: #af1212;
  opacity: 0;
  transition: all 0.3s ease;
}

.selector {
  /* 选择框样式 */
  width: 50px;
  height: 50px;
}

.info {
  /* 图片信息样式 */
  margin: 50% 0;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  color: #ffff;
}

/* 当鼠标移入时，遮罩层变为不透明 */
.image-container:hover .overlay {
  opacity: 1;
  cursor: pointer;
}

.flex {
  display: flex;
  flex-wrap: wrap; /* 允许内容换行 */
  justify-content: flex-start; /* 水平方向从左侧对齐 */
  align-items: flex-start; /* 垂直方向从顶部对齐 */
}
.flex:after {
  content: "";
  display: block;
  width: 100%;
}

.hiddn {
  white-space: nowrap; /* 指定文本不换行 */
  overflow: hidden; /* 文本超出容器时隐藏 */
  text-overflow: ellipsis;
}

.media-input {
  width: 880px;
}

.tabs {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  border-bottom: 1px solid $borderColor;
  margin-bottom: 20px;
}

.tab {
  padding: 0 10px 8px;
  border-bottom: 2px solid transparent;
  cursor: pointer;

  &.active {
    border-bottom: 2px solid $themeColor;
  }
}

.btns {
  margin-top: 10px;
  text-align: right;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  background: #f6f7f9;
  border-radius: 4px;

  width: 150px;
  height: 150px;
  text-align: center;
}
</style>
